package com.td.library.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.app.Context;
import ohos.data.rdb.ValuesBucket;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.*;

/**
 * 文件操作工具类
 */
public class FileUtils {
    private static final String TAG = "FileUtils";

    private static final String RELATIVE_PATH = "/fileManager/";

    // 缓存大小8M
    private static final int CACHE_SIZE = 8 * 1024;

    // 结束下标
    private static final int END_OF_FILE = -1;

    /**
     * 保存文件到本地
     *
     * @param context 上下文
     * @param inputStream 输入流
     * @param path  路径
     * @param filename  文件名
     *
     * @return 是否成功
     */
    public static boolean saveToDownloads(Context context, InputStream inputStream, String path, String filename) {
        LogUtil.debug(TAG, "saveToAlbum path " + path);
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        String[] projections = new String[]{
                AVStorage.AVBaseColumns.ID,
                AVStorage.AVBaseColumns.DISPLAY_NAME,
                AVStorage.AVBaseColumns.DATA
        };
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.AVBaseColumns.DATA, path);
            valuesBucket.putString(AVStorage.AVBaseColumns.DISPLAY_NAME, filename);
            // 应用独占
            valuesBucket.putInteger("is_pending", 1);

            int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            // 这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(fd);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
            } catch (Exception e) {
                LogUtil.error(TAG, "IOException " + e.getMessage());
            } finally {
                valuesBucket.clear();
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            // 解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.debug(TAG, "IOException " + e.getMessage());
        }
        return false;
    }

    /**
     *
     * @return 获取文件的后缀名。
     */
    public static String getFileSuffix(String fileName) {
        if (fileName == null) {
            return "";
        }
        int idx = fileName.lastIndexOf(".");
        String suffix;
        if (idx < 0) {
            suffix = "";
        } else {
            suffix = fileName.substring(idx + 1);
        }
        return suffix;
    }

    /**
     * 获取文件名
     *
     * @param fileName 文件全路径名
     * @return 文件名
     */
    public static String getFileName(String fileName) {
        if (fileName == null) {
            return "";
        }
        int idx = fileName.lastIndexOf(File.separator);
        String name;
        if (idx < 0) {
            name = "";
        } else {
            name = fileName.substring(idx + 1);
        }
        return name;
    }

    /**
     * 拷贝文件
     *
     * @param inputStream 输入流
     * @param outputStream 输出流
     */
    public static void copyFile(InputStream inputStream, OutputStream  outputStream) {
        try {
            byte[] buffer = new byte[CACHE_SIZE];
            int count;
            while ((count = inputStream.read(buffer)) != END_OF_FILE) {
                outputStream.write(buffer, 0, count);
            }
        } catch (IOException e) {
            LogUtil.error(TAG, "write to distribute dir error: " + e);
        } finally {
            try {
                // 关闭输入流
                if (inputStream != null) {
                    inputStream.close();
                }
                // 关闭输出流
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                LogUtil.error(TAG, "close input stream error");
            }
        }
    }
}
